package com.example.demo;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;

/**
 * @Desc
 * @Author zxp
 * @Date 2024/3/17
 */
// 指定有哪些表，指定当前数据库版本号（表更改要改版本号，版本号变动需要Migration），不导出数据库
@Database(entities = {User.class}, version = 2, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    private static final String DATABASE_NAME = "database_name.db";

    private static volatile AppDatabase instance;

    // 版本1到版本2
    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            // 操作
//            database.execSQL(xxx);
        }
    };

    public static AppDatabase getInstance(Context context) {
        if (instance == null) {
            synchronized (AppDatabase.class) {
                if (instance == null) {
                    instance = Room.databaseBuilder(
                            context,
                            AppDatabase.class,
                            DATABASE_NAME)
                            .addMigrations(MIGRATION_1_2)
                            .build();
                }
            }
        }
        return instance;
    }

    public abstract UserDao getUserDao();
}
